package com.itlong.cloud.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.old.AppOldUserInfoDto;
import com.itlong.cloud.POJO.PO.AdPO;
import com.itlong.cloud.POJO.PO.AppPublishInfoPO;
import com.itlong.cloud.POJO.PO.PropertyInfoPO;
import com.itlong.cloud.POJO.VO.app.old.AppOldAdVo;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.app.dao.IAppOldRegisterDao;
import com.itlong.cloud.app.dao.IAppOldServeDao;
import com.itlong.cloud.app.service.IAppOldServeService;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.oldapp.Code;
import com.itlong.cloud.enumerate.oldapp.Message;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *     旧版APP的服务版块接口实现
 * </desc>
 * Created 2017/11/13.
 */
@Service
@RefreshScope
public class AppOldServeServiceImpl implements IAppOldServeService{
    @Value("${" + PlatformConstants.COMPANY_WEBSIT_URL + "}")
    public String COMPANY_WEBSIT_URL;
    @Value("${" + PlatformConstants.COMPANY_APP_DEFAULT_IMG + "}")
    public String COMPANY_APP_DEFAULT_IMG;



    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;


    @Autowired
    IAppOldRegisterDao iAppOldRegisterDao;
    @Autowired
    IAppOldServeDao iAppOldServeDao;


    /**
     * <desc>
     *     旧版APP_获取服务版块的广告
     * </desc>
     * @param type
     * @param phoneNo
     * @param projectId
     * @return
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/13
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message getAd(String phoneNo,String projectId,String type) throws Exception{
        AppOldUserInfoDto appOldUserInfoDto = iAppOldRegisterDao.selectDtoByPhone(phoneNo);
        if (appOldUserInfoDto == null){
            return  new Message(Code.TOKEN_ERR);
        }
        if (StringUtils.isBlank(type)) {
            type = "2";
        }
        JSONObject data = new JSONObject();
        Map<String,Object> params = new HashMap<>();
        params.put("userId",appOldUserInfoDto.getUserId());
        params.put("type",type);
        if (StringUtils.isNotBlank(projectId)){
            params.put("projectId",projectId);
        }
        params.put("status",1);
        params.put("currentPage",1);
        params.put("pageSize",3);
        List<AppOldAdVo> oldAds = new ArrayList<>();
        List<AdPO> ads = new ArrayList<>();
        ads = iAppOldServeDao.getAdByPage(params);
        if (ads != null&&ads.size()>0){
            for (AdPO adPO:ads){
                AppOldAdVo appOldAdVo = new AppOldAdVo(adPO.getAdId(),adPO.getTitle(),adPO.getType()+"",adPO.getTitle());
                List<Map<String,Object>> adImagList = iAppOldServeDao.getImageByAd(adPO.getAdId());
                if (adImagList != null&&adImagList.size()>0){
                    appOldAdVo.setImgUrl(adImagList.get(0).get("imgUrl").toString());
                    appOldAdVo.setJumpUrl(adImagList.get(0).get("jUrl").toString());
                }
                oldAds.add(appOldAdVo);
            }
        }else {
            AppOldAdVo appOldAdVo = new AppOldAdVo(LogicIdUtil.bussinessId(),"欢迎使用云半径!","2","欢迎使用云半径!");
            appOldAdVo.setImgUrl(COMPANY_APP_DEFAULT_IMG);
            appOldAdVo.setJumpUrl(COMPANY_WEBSIT_URL);
            oldAds.add(appOldAdVo);
        }
        data.put("ads",oldAds);
        return  new Message(Code.SUCCESS,data);
    }
    /**
     * <desc>
     *     旧版APP_用户报修或投诉
     * </desc>
     * @param phoneNo
     * @param imageStr
     * @param imageType
     * @param propertyInfo
     * @param projectId
     * @param type 3-报修，4-投诉
     * @return
     * @throws Exception
     * @author cuiduanwu
     * @createDate 2017/11/13
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message addReportRepairOrComplaint(String phoneNo,String imageStr,String imageType,String propertyInfo,String projectId,String type) throws Exception{
        AppOldUserInfoDto appOldUserInfoDto = iAppOldRegisterDao.selectDtoByPhone(phoneNo);
        if (appOldUserInfoDto == null){
            return  new Message(Code.TOKEN_ERR);
        }
        String imgUrl = "";
        if (StringUtils.isNotBlank(imageStr)){
            String[] imgArr = imageStr.split(",");
            String[] imgTypeArr = imageType.split(",");
            for (int i=0;i<imgArr.length;i++){
                String imgresult = this.uploadImg(URLDecoder.decode(imgArr[i],"UTF-8"),imgTypeArr[i],type);
                if (StringUtils.isEmpty(imgUrl)){
                    imgUrl = imgresult;
                }else {
                    imgUrl = imgUrl+","+imgresult;
                }
            }
        }
        PropertyInfoPO propertyInfoPO = new PropertyInfoPO(LogicIdUtil.bussinessId(),projectId,Integer.parseInt(type),propertyInfo,imgUrl,appOldUserInfoDto.getUserId());
        propertyInfoPO.setStatus(1);
        boolean flag = iAppOldServeDao.savePropertyInfo(propertyInfoPO)>0?true:false;
        if (flag){
            return  new Message(Code.SUCCESS);
        }else {
            return new Message(Code.ERROR);
        }
    }

    /**
     * <desc>
     *     旧版APP_上传报修与投诉图片
     * </desc>
     * @param imageStr
     * @param imageType
     * @param type 3-报修，4-投诉
     * @return
     * @throws Exception
     */
    public String uploadImg(String imageStr,String imageType,String type) throws Exception{
        String imageUrl = null;
        String fileDir = FileCatalogEnum.PROPERTYREPAIR_FILE.getType();
        if ("4".equals(type)){
            fileDir = FileCatalogEnum.FEEDBACK_FILE.getType();
        }
        try {
            byte[] bytes = new BASE64Decoder().decodeBuffer(imageStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                    FILE_FTP_HOST,
                    FILE_FTP_USERNAME,
                    FILE_FTP_PASSWORD,
                    FILE_FTP_PORT,
                    byteArrayInputStream,
                    imageType,
                    FILE_ACCESS_URL,
                    fileDir
            );
            Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
            if ("true".equals(resultMap.get("returnCode").toString())){
                imageUrl = resultMap.get("accessPath").toString();
                return  imageUrl;
            }else {
                return  imageUrl;
            }
        }catch (Exception e){
            throw new DataAccessException("【旧版APP_上传报修投诉图片】报修投诉图片上传失败",e);
        }
    }





    /**
     * <desc>
     *     旧版APP_检测APP版本
     * </desc>
     * @param type android/ios/iossdk/androidsdk
     * @param sort test/official
     * @return
     * @author cuiduanwu
     * @createDate 2017/11/14
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Message getLatestApp(String type,String sort){
        JSONObject js = null;
        AppPublishInfoPO appPublishInfoPO = iAppOldServeDao.getLatestApp(type,sort);
        if (appPublishInfoPO != null){
            js = (JSONObject)JSONObject.toJSON(appPublishInfoPO);
            js.put("autoIndex",LogicIdUtil.bussinessId());
            js.put("appDownloadUrl",appPublishInfoPO.getAppDownUrl());
        }
        return  new Message(Code.SUCCESS,js);
    }














}
